package com.pactera.madp.cp.controller.oms;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.constant.DeptConstants;
import com.pactera.madp.cp.api.dto.AddCustomerQueryDTO;
import com.pactera.madp.cp.api.entity.AddCustomerEntity;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.AddCustomerStatisticsVO;
import com.pactera.madp.cp.api.vo.AddCustomerVO;
import com.pactera.madp.cp.service.AddCustomerService;
import com.pactera.madp.cp.service.IWorkDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.LinkedHashMap;

/**
 * (CpAddCustomer)表控制层
 *
 * @author yushen.qi
 * @since 2022-01-11 18:17:23
 */
@RestController
@RequestMapping("/add-customer")
@Api(value = "addCustomer", tags = "批量添加客户管理")
public class AddCustomerController extends ApiController {

    /**
     * 服务对象
     */
    @Autowired
    private AddCustomerService addCustomerService;
    /**
     * 远程调用部门信息
     */
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private IWorkDeptService workDeptService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public R getPage(Page page) {
        return R.ok( addCustomerService.getListPage(page));
    }

    @GetMapping("/msg")
    @ApiOperation(value = "提醒客户经理批量")
    public void msg(){
        addCustomerService.toEmployee();
    }

    @GetMapping("/msg-one")
    @ApiOperation(value = "提醒客户经理")
    public void msgOne(@RequestParam String employeeId,@RequestParam Integer id) {
       addCustomerService.toEmployeeOne(employeeId, id);
    }

    @GetMapping("/change")
    @ApiOperation(value = "改变状态")
    public R change(String employeeId, Integer id) {
       boolean update = addCustomerService.update(null, new UpdateWrapper<AddCustomerEntity>()
               .set("state", 2)
               .eq("employee_id", employeeId)
               .eq("id", id));
       return  update?R.ok(null,"已确认添加！"):R.failed("确认失败！");
    }

    @GetMapping("/crm-cust-page")
    @ApiOperation(value = "华融湘江CRM客户分页查询")
    public R<IPage<AddCustomerVO>> getCrmCustPage(Page page, AddCustomerQueryDTO dto){
        return R.ok(addCustomerService.getCrmCustPage(page,dto)) ;
    }

    @GetMapping("/statistics/{deptId}")
    @ApiOperation(value = "华融湘江CRM客户数据统计")
    public R<AddCustomerStatisticsVO> getStatistics(@PathVariable("deptId")Integer deptId) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        return R.ok(addCustomerService.getStatisticsDatas(deptId,wxDeptId));
    }

    @GetMapping("/statistics-page/{deptId}")
    @ApiOperation(value = "华融湘江CRM客户数据统计分页")
    public R<IPage<AddCustomerStatisticsVO>> getStatisticsPage(Page page,@PathVariable("deptId") Integer deptId){
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .select(WorkDeptEntity::getLevel)
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        Integer level = workDeptEntity.getLevel();
        if (level < DeptConstants.SUB_BRANCH_LEVEL) {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getChildrenPage(deptId, page).getData();
            Page<AddCustomerStatisticsVO> vos = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<AddCustomerStatisticsVO>>() {});
            vos.getRecords().forEach(s -> {
                AddCustomerStatisticsVO entity1 = addCustomerService.getStatisticsDatas(s.getId(), Integer.parseInt(s.getCode()));
                s.setCrmCustTotalCount(entity1.getCrmCustTotalCount());
                s.setDistributedCount(entity1.getDistributedCount());
                s.setUndistributedCount(entity1.getUndistributedCount());
                s.setAddedCount(entity1.getAddedCount());
                s.setAddedPercentage(entity1.getAddedPercentage());
                s.setCode(s.getName());
                s.setName(entity1.getName());
            });
            SubPage subPage = new SubPage();
            subPage.setRecords(vos.getRecords());
            subPage.setSize(vos.getSize());
            subPage.setCurrent(vos.getCurrent());
            subPage.setTotal(vos.getTotal());
            subPage.setPages(vos.getPages());
            return R.ok(subPage);
        } else {
            return R.ok(new SubPage());
        }
    }

    @GetMapping("/list/{wxUserId}")
    @ApiOperation(value = "根据wxUserId获取CRM客户列表")
    public R getListByWxUserId(@PathVariable String wxUserId) {
        return R.ok(addCustomerService.getListByWxUserId(wxUserId));
    }

    @PostMapping("/input-excel")
    @ApiOperation(value = "Excel导入CRM客户数据")
    public R inputCrmCustData(@RequestParam(name = "file") MultipartFile file) {
        return addCustomerService.inputCrmCustData(file);
    }

    @PostMapping("/output-excel")
    @ApiOperation(value = "Excel模板导出")
    public void exitExcel(HttpServletResponse response, OutputStream out){
        addCustomerService.outputExcel(response,out);
    }

}
